#ifndef ____UDP_HPP____
#define ____UDP_HPP____
#include <unistd.h>
#include <iostream>
#include <string>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>

class UdpServer
{
public:
    UdpServer(uint16_t port)
        : _port(port), _socketfd(-1), _isrunning(false)
    {
    }

    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            perror("socket");
            exit(1);
        }
        struct sockaddr_in _siny;
        memset(&_siny, 0, sizeof(_siny));
        _siny.sin_family = AF_INET;
        _siny.sin_addr.s_addr = htonl(INADDR_ANY);
        _siny.sin_port = htons(_port);
        int n = bind(_socketfd, (struct sockaddr *)&_siny, sizeof(_siny));
        if (n < 0)
        {
            perror("bind");
            exit(1);
        }
    }

    void Start()
    {
        if (_isrunning)
            return;
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024] = {0};
            struct sockaddr_in _sender;
            memset(&_sender, 0, sizeof(_sender));
            socklen_t len = sizeof(_sender);
            ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&_sender, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;
                sendto(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&_sender, len);
            }
        }
        _isrunning = false;
    }

    void Stop()
    {
        _isrunning = false;
    }

    ~UdpServer()
    {
    }

private:
    uint16_t _port;
    int _socketfd;
    bool _isrunning;
};



#endif